home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Personal Computer World 2009 February
/
PCWFEB09.iso
/
Software
/
Resources
/
Chat & Communication
/
Digsby build 37
/
digsby_setup.exe
/
lib
/
gui
/
input
/
inputmanager.pyo
(
.txt
)
< prev
Wrap
Python Compiled Bytecode
|
2008-10-13
|
11KB
|
357 lines
# Source Generated with Decompyle++
# File: in.pyo (Python 2.5)
from __future__ import with_statement
from traceback import print_exc
from collections import defaultdict
from util import Delegate, import_function, memoize
from util.merge import merge_keys
from prefs import flatten
import wx
from wx import WXK_F1, WXK_F24, wxEVT_KEY_DOWN
from logging import getLogger
log = getLogger('input')
DEBUG = log.debug
class InputManager(object):
def __init__(self):
self.reset()
def reset(self):
self.handlers = defaultdict(Delegate)
self.actions = defaultdict(dict)
self.contexts = []
self.context_lookups = []
self.actionnames = { }
self.context_cache = { }
self.bound = False
def AddGlobalContext(self, name, contextstr):
self.context_lookups.append((contextstr.lower(), GlobalContext()))
self.context_cache.clear()
self.resolve_actions()
def AddClassContext(self, name, contextstr, cls):
self.context_lookups.append((contextstr.lower(), ClassContext(name, cls)))
self.context_cache.clear()
self.resolve_actions()
def AddKeyboardShortcut(self, actionname, accels):
keys = (KeyActionSet,)((lambda .0: for accel in .0:
(keycodes(accel), actionname))(accels.split(',')))
self.actionnames[actionname.lower()] = keys
self.resolve_actions()
def LoadKeys(self, filepath):
addkey = self.AddKeyboardShortcut
import syck as syck
try:
f = _[2]
for actionname, accels in flatten(merge_keys(syck.load(f))):
addkey(actionname, accels)
finally:
pass
def resolve_actions(self):
if not self.bound:
return None
contexts = set()
find_context = self.find_context
for actionname, actionset in self.actionnames.iteritems():
context = find_context(actionname)
if context is not None:
try:
keyactions = self.actions[wxEVT_KEY_DOWN][context]
except KeyError:
keyactions = self.actions[wxEVT_KEY_DOWN][context] = KeyActionSet()
keyactions.update(actionset)
contexts.add(context)
continue
self.contexts = sorted(contexts, reverse = True)
def AddActionCallback(self, actionname, callback):
actionname = actionname.lower()
if isinstance(callback, basestring):
callback = LazyStringImport(callback)
if actionname not in self.handlers:
self.handlers[actionname] = Delegate([
callback])
else:
self.handlers[actionname] += callback
self.resolve_actions()
def BindWxEvents(self, evt_handler):
if self.bound is not evt_handler:
evt_handler.Bind(wx.EVT_KEY_DOWN, self.handle_event)
self.bound = evt_handler
self.resolve_actions()
def find_context(self, actionname):
if actionname in self.context_cache:
return self.context_cache[actionname]
actionname = actionname.lower()
startswith = actionname.startswith
found = _[1]
found.sort(key = (lambda s: len(s[0])), reverse = True)
context = [] if found else None
return self.context_cache.setdefault(actionname, context)
def handle_event(self, e):
contexts = self.contexts
for win in child_and_parents(e.EventObject):
for context in contexts:
if context(win):
if self.invoke_actions(context, e, win) is False:
return None
self.invoke_actions(context, e, win) is False
e.Skip()
def invoke_actions(self, context, e, win):
try:
actionset = self.actions[e.EventType][context]
except KeyError:
return None
try:
actionname = actionset(e, win)
if actionname is False:
return None
elif actionname is not None:
return self.event(actionname, win)
except Exception:
print_exc()
def event(self, actionname, *a, **k):
try:
DEBUG('firing action %r', actionname)
action_delegate = self.handlers[actionname]
DEBUG(' callbacks: %r', action_delegate)
except KeyError:
pass
try:
if action_delegate:
action_delegate(*a, **k)
return False
except Exception:
print_exc()
class Context(object):
__slots__ = [
'name']
priority = 0
def __init__(self, name):
self.name = name
def __call__(self):
raise NotImplementedError('Context subclasses must implement __call__')
def __cmp__(self, other):
return cmp(self.priority, other.priority)
def __hash__(self):
return hash(id(self))
class WindowNameContext(Context):
__slots__ = [
'window_name']
priority = 100
def __init__(self, name, window_name):
Context.__init__(self, name)
self.window_name = window_name
def __call__(self, window):
return window.Name == self.window_name
def __repr__(self):
return '<WindowNameContext %r>' % self.window_name
class ClassContext(Context):
__slots__ = [
'cls']
priority = 90
def __init__(self, name, cls):
Context.__init__(self, name)
self.cls = cls
def __call__(self, window):
return isinstance(window, self.cls)
def __repr__(self):
return '<ClassContext %r>' % self.cls
class GlobalContext(Context):
priority = 10
def __init__(self, name = 'Global Shortcuts'):
Context.__init__(self, name)
def __call__(self, window, tlw = wx.TopLevelWindow):
return isinstance(window, tlw)
def __repr__(self):
return '<GlobalContext %s>' % self.name
class KeyActionSet(dict):
def __call__(self, e, win):
keycode = e.KeyCode
if keycode <= keycode:
pass
elif keycode <= WXK_F24:
pass
elif keycode < 256:
keycode = ord(chr(keycode).upper())
key = (e.Modifiers, keycode)
return self.get(key, None)
def child_and_parents(win):
yield win
win = getattr(win, 'Parent', None)
while win is not None:
yield win
win = win.Parent
def _accelerr(s):
raise ValueError('illegal accelerator: like "cmd+k" or "k" (you gave "%s")' % s)
replacements = {
'backspace': 'back',
'capslock': 'capital',
'=': 43 }
def keycodes(s, accel = True):
if isinstance(s, basestring):
s = s.strip()
seq = s.split('+')
for i, _elem in enumerate(seq[:]):
if _elem == '':
seq[i] = '+'
continue
if len(seq) == 1:
modifiers = [
'normal']
key = s
else:
modifiers = seq[:-1]
key = seq[-1]
elif not isinstance(s, int):
_accelerr(s)
modifiers = [
'normal']
key = s
modifier = 0
PREFIX = None if accel else 'MOD_'
for mod in modifiers:
modifier |= getattr(wx, PREFIX + mod.upper())
if isinstance(key, basestring):
if len(key) == 1 and key not in replacements:
key = ord(key.upper())
else:
key = replacements.get(key.lower(), key)
if isinstance(key, basestring):
try:
key = getattr(wx, 'WXK_' + replacements.get(key.lower(), key).upper())
except AttributeError:
_accelerr(s)
except:
None<EXCEPTION MATCH>AttributeError
None<EXCEPTION MATCH>AttributeError
return (modifier, key)
keycodes = memoize(keycodes)
class LazyStringImport(str):
def __call__(self, *a, **k):
try:
return self.cb()
except TypeError:
e = None
if e.message.endswith('takes exactly 1 argument (0 given)'):
return self.cb(*a, **k)
else:
raise
except:
e.message.endswith('takes exactly 1 argument (0 given)')
def cb(self):
try:
return self._cb
except AttributeError:
self._cb = import_function(self)
return self._cb
cb = property(cb)
input_manager = InputManager()